package com.godtree.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;




public class UserDao2 {
	String url="jdbc:mysql://localhost/jspdemo?useUnicode=true&characterEncoding=UTF-8";
	String userName="root";
	String passWord="hideapple";
	Connection con=null;
	ResultSet rs=null;
	PreparedStatement preparedStatement=null;
	public UserDao2()
	{
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		System.out.println("数据库连接包2加载成功!");
    	}catch(ClassNotFoundException e){
    		System.err.println("con():"+e.getMessage());
    	}
    }
	public void createUser(String name,String password) {
		try {
			con=DriverManager.getConnection(url,userName,passWord);
			preparedStatement = con.prepareStatement("insert into user(name,password) values(?,?)");
			preparedStatement.setString(1,name);
			preparedStatement.setString(2,password);
			preparedStatement.execute();
			/*
			这里的测试让我知道了,preparedStatement.execute()如果有返回值的话就是true,如果没有就是flase
			System.out.println("执行结果:"+preparedStatement.execute());
			*/
			long ret_id=0;
			ResultSet rs = preparedStatement.executeQuery("select LAST_INSERT_ID()");
			if (rs.next()) ret_id = rs.getLong(1);
			System.out.println("刚插入数据的id是"+ret_id);
			Close2();
			System.out.println("数据库关闭");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public ResultSet queryUser(String name){
		try {
			con=DriverManager.getConnection(url,userName,passWord);
			preparedStatement = con.prepareStatement("select * from user where name=?");
			preparedStatement.setString(1,name);
			rs=preparedStatement.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("查询报错");
		}
		return rs;
	}
	   public void Close1()
	    {
	    	try{
	    		rs.close();
	    		preparedStatement.close();
	    		con.close();
	    	}catch(SQLException e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    public void Close2()
	    {
	    	try{
	    		preparedStatement.close();
	    		con.close();
	    	}catch(SQLException e){
	    		e.printStackTrace();
	    	}
	    }
}
